package nsqUtils

import (
	"fmt"
	"github.com/nsqio/go-nsq"
	"time"
)

type NsqProducer struct {
	addr     string
	producer *nsq.Producer
}

func NewPublisher(addr string) *NsqProducer {
	return &NsqProducer{addr: addr}
}

func (n *NsqProducer) InitProducer(config *nsq.Config) *NsqProducer {
	var err error
	n.producer, err = nsq.NewProducer(n.addr, config)
	if err != nil {
		fmt.Printf("create producer failed, err:%v\n", err)
		panic(err)
	}
	return n
}

func (n *NsqProducer) Publish(topic string, body []byte) error {
	err := n.producer.Publish(topic, body)
	if err != nil {
		fmt.Printf("publish msg to nsq failed, err:%v\n", err)
	}
	return err
}
func (n *NsqProducer) MPublish(topic string, body [][]byte) {
	err := n.producer.MultiPublish(topic, body)
	//err := n.producer.DeferredPublish(topic, body)
	if err != nil {
		fmt.Printf("publish msg to nsq failed, err:%v\n", err)
	}
}
func (n *NsqProducer) DeferredPublish(topic string, body []byte, delay time.Duration) {
	err := n.producer.DeferredPublish(topic, delay, body)
	if err != nil {
		fmt.Printf("deferredPublish msg to nsq failed, err:%v\n", err)
	}
}
